package sudoku;

import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JLabel;

public class Chronometre {
	Timer timer;
	JLabel label;
	int secondes=-1, minutes=0, heures=0;
	String str;
	Chrono chrono;
	long lastUpdate;
	boolean pause = false;

	public Chronometre(JLabel lab) {
		label = lab;
		timer = new Timer();
		chrono = new Chrono();
		timer.schedule(chrono, 0, 1000);
	}

	class Chrono extends TimerTask {
		public void run() {
			secondes++;
			if (secondes==60){
				secondes=0;
				minutes++;
			}
			if (minutes==60){
				minutes=0;
				heures++;
			}
			if (heures<10){
				str = "0"+heures;
			} else {
				str = ""+heures;
			}
			str = str+":";
			if (minutes<10){
				str = str+"0"+minutes;
			} else {
				str = str+minutes;
			} str = str+":";
			if (secondes<10){
				str = str+"0"+secondes;

			} else {
				str = str+secondes;
			}
			label.setText(str);
			lastUpdate = System.currentTimeMillis();
		}
	}
	
	public void setTimer(int sec, int min, int heure, int lastUp){
		secondes = sec-1;
		minutes = min;
		heures = heure;
		timer.cancel();
		timer = new Timer();
		chrono = new Chrono();
		timer.schedule(chrono, lastUp, 1000);
	}

	public void pause(){
		pause = true;
		lastUpdate -= System.currentTimeMillis();
		lastUpdate *= -1;
		timer.cancel();
	}

	public void unpause(){
		timer = new Timer();
		chrono = new Chrono();
		timer.schedule(chrono, 1000-lastUpdate, 1000);
		pause = false;
	}

	public String getTimer(){
		if (pause) {
			return secondes+":"+minutes+":"+heures+":"+(1000-lastUpdate);
		} else {
			return secondes+":"+minutes+":"+heures+":"+(1000-(System.currentTimeMillis()-lastUpdate));
		}
		
	}
	public void stop(){
		if (!pause){
			timer.cancel();
		}
		label.setText("Chronometre inactif");	
		secondes=-1; minutes=0; heures=0;
	}
}
